package jjn.daily;

/**
 * @author Jiang Jining
 * @since 2023-07-13 23:40
 */
public class LeetCode931 {
    public int minFallingPathSum(int[][] matrix) {
        int[][] dp = new int[matrix.length][matrix[0].length];
        System.arraycopy(matrix[0], 0, dp[0], 0, matrix[0].length);
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int val = matrix[i][j];
                int minFromLastRow = getMinFromLastRow(i, j, dp);
                System.out.println("val = " + val);
                System.out.println("minFromLastRow = " + minFromLastRow);
                dp[i][j] = minFromLastRow + val;
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < matrix.length; i++) {
            min = Math.min(dp[matrix.length - 1][i], min);
        }
        return min;
    }
    
    private int getMinFromLastRow(int i, int j, int[][] dp) {
        int length = dp[0].length;
        int left = Math.max(0, j - 1);
        int right = Math.min(j + 1, length - 1);
        int min = dp[i - 1][j];
        while (left <= right) {
            min = Math.min(dp[i - 1][left], min);
            left++;
        }
        return min;
    }
    
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{2, 1, 3}, {6, 5, 4}, {7, 8, 9}};
        int minFallingPathSum = new LeetCode931().minFallingPathSum(matrix);
        System.out.println("minFallingPathSum = " + minFallingPathSum);
    }
}
